package com.mogu.oauth.Controller;

import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.net.URLEncoder;
import java.util.UUID;

/**
 * Created by Papa on 2020/6/17.
 */
@Api(value = "OAuth第三方授权相关接口", tags = {"第三方授权相关接口"})
@RestController
public class GitHubController {
    @Value("${github.oauth.clientid}")
    public String CLIENTID;
    @Value("${github.oauth.clientsecret}")
    public String CLIENTSECRET;
    @Value("${github.oauth.callback}")
    public String URL;
    @GetMapping(value = "/auth")
    public String GithubAuth(HttpSession session) {
        // 用于第三方应用防止CSRF攻击
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        session.setAttribute("state", uuid);

        // Step1：获取Authorization Code
        String url = "https://github.com/login/oauth/authorize?scope=user" +
                "&client_id=" + CLIENTID +
                "&redirect_uri=" + URLEncoder.encode(URL) +
                "&state=" + uuid;

        return url;
    }

    @GetMapping(value = "/oauth/redirect")
    public Object Callback(HttpServletRequest request,Model model) throws Exception {
        HttpSession session = request.getSession();
        // 得到Authorization Code
        String code = request.getParameter("code");
        // 我们放在地址中的状态码
        String state = request.getParameter("state");
        String uuid = (String) session.getAttribute("state");

        // 验证信息我们发送的状态码
        if (null != uuid) {
            // 状态码不正确，直接返回登录页面
            if (!uuid.equals(state)) {
                return "fail";
            }
        }

        // Step2：通过Authorization Code获取Access Token
        String url = "https://github.com/login/oauth/access_token?" +
                "client_id=" + CLIENTID +
                "&client_secret=" + CLIENTSECRET +
                "&redirect_uri=" + URL +
                "&code=" + code +
                "&state=" + state;

        JSONObject accessTokenJson = GithubHttpClient.getAccessToken(url);
        System.out.println(accessTokenJson);
        // Step3: 获取用户信息
    /*url = "https://api.github.com/user?access_token=" + accessTokenJson.getString("access_token");*/
        url = "https://api.github.com/user";
        JSONObject jsonObject = GithubHttpClient.getUserInfo(url,accessTokenJson.getString("access_token"));
        System.out.println(jsonObject);
//        model.addAttribute(jsonObject);
        return jsonObject;
    }

}
